package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;

/**
 * 搜索手机号加入宝宝日记
 */
public class Select3Fragment extends BaseFragment implements View.OnTouchListener, View.OnClickListener {

    private CuteEditText mInputPhone;

    private TextInputLayout inputLayoutPhone;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case (1):
                if (resultCode == Activity.RESULT_OK) {

                    Uri contactData = data.getData();
                    Cursor c = getActivity().managedQuery(contactData, null, null, null, null);
                    if (c.moveToFirst()) {


                        String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                        String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                        if (hasPhone.equalsIgnoreCase("1")) {
                            Cursor phones = getActivity().getContentResolver().query(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                                    null, null);
                            phones.moveToFirst();
                            String cNumber = phones.getString(phones.getColumnIndex("data1"));
                            cNumber = cNumber.replace(" ", "");
                            cNumber = cNumber.replace("-", "");
                            cNumber = cNumber.substring(cNumber.length() - 11, cNumber.length());
                            mInputPhone.setText(cNumber);
                            phones.close();
                        }
                    }
                }
                break;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_create3, container, false);
        inputLayoutPhone = (TextInputLayout) view.findViewById(R.id.text_input_layout_phone);
        inputLayoutPhone.setHint("手机号?");
        CuteButton buttonSearch = (CuteButton) view.findViewById(R.id.button_search);
        mInputPhone = (CuteEditText) view.findViewById(R.id.text_input_phone);
        buttonSearch.setOnClickListener(this);
        mInputPhone.setOnTouchListener(this);

        mInputPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    inputLayoutPhone.setError(null);
                } else {
                    inputLayoutPhone.setError("手机格式有误");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        return view;
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_RIGHT = 2;

        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (event.getRawX() >= (mInputPhone.getRight() - mInputPhone.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                // Create an intent to "pick" a contact, as defined by the content provider URI
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 1);
                return true;
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_search) {
            String searchPhone = mInputPhone.getText().toString();
            if (TextUtils.isEmpty(searchPhone) || searchPhone.length() != 11) {
                tipShow("请输入正确的手机号");
                return;
            }
            Intent intent = new Intent(getActivity(), JoinActivity.class);
            intent.putExtra("searchPhone", mInputPhone.getText().toString());
            startActivity(intent);
            getActivity().finish();
        }
    }
}
